from dao.user_collection_dao import UserCollectionDao


class UserCollectionService:
    def __init__(self, session):
        self.session = session

    def add(self, message):
        dao = UserCollectionDao(self.session)
        dao.add(message)

    def get_collection_by_job_uid(self, job_id, user_id):
        dao = UserCollectionDao(self.session)
        return dao.get_collection_by_job_uid(job_id, user_id)

    def get_collection_by_user_id(self, d={}):
        a_list = []
        dao = UserCollectionDao(self.session)
        result = dao.get_collection_by_user_id(d)
        if result:
            for d in result:
                a_list.append(d.json())
            return a_list
        else:
            return None

    def get_self_collection(self, user_id):
        a_list = []
        sql = """
        SELECT a.collection_id,a.user_id,a.job_id,b.job_name,b.job_time,
        b.job_place,c.company_id,c.`name`,a.collect_date
        FROM user_collection a
        JOIN job b ON a.job_id = b.job_id
        join company c
        on b.company_id=c.company_id
        WHERE a.user_id =:user_id ORDER BY	a.create_time DESC
        """
        result = self.session.execute(sql,{"user_id":user_id})
        if result:
            for d in result:
                a_list.append({
                    'collection_id': d["collection_id"],
                    'user_id': d["user_id"],
                    'job_id': d["job_id"],
                    'job_name': d["job_name"],
                    'company_id': d["company_id"],
                    'collect_date': d["collect_date"],
                    'job_place': d["job_place"],
                    'job_time': d["job_time"]
                })
            return a_list
        else:
            return None
